/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package luft27.zorcon.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
import luft27.zorcon.input.InputDetector;
import luft27.propertytree.PropertyNode;
import luft27.propertytree.PropertyTree;
import luft27.propertytree.PropertyValue;

/**
 *
 * @author amalikov
 */
public class ControlSettingsDialog extends javax.swing.JDialog {

	/**
	 * Creates new form ControlSettingsDialog
	 */
	public ControlSettingsDialog(java.awt.Frame parent, boolean modal) {
		super(parent, modal);
		initComponents();

		PropertyNode input = PropertyTree.INSTANCE.getNode("/settings/input");
		controlElements = new ControlElement[controlNames.length];		
		for (int i = 0; i < controlNames.length; ++i) {
			controlElements[i] = new ControlElement(
					controlNames[i], 
					input.get("/" + controlNames[i] + "/controller").asString(), 
					input.get("/" + controlNames[i] + "/component").asString(), 
					input.get("/" + controlNames[i] + "/inverted").asBool());
		}
		
		updateTable();
	}

	/**
	 * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.JButton ok = new javax.swing.JButton();
        javax.swing.JButton cancel = new javax.swing.JButton();
        javax.swing.JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Control settings");
        setLocationByPlatform(true);
        setResizable(false);

        ok.setText("OK");
        ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okActionPerformed(evt);
            }
        });

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        table.setModel(new DefaultTableModel());
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        table.getTableHeader().setReorderingAllowed(false);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(table);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(ok, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancel)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 549, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancel)
                    .addComponent(ok))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed
		PropertyNode input = PropertyTree.INSTANCE.getNode("/settings/input");
		for (ControlElement c : controlElements) {
			input.set("/" + c.name + "/controller", new PropertyValue(c.controller));
			input.set("/" + c.name + "/component", new PropertyValue(c.component));
			input.set("/" + c.name + "/inverted", new PropertyValue(c.inverted));
		}
		PropertyTree.INSTANCE.set("/settings", new PropertyValue(0));
		setVisible(false);
	}//GEN-LAST:event_okActionPerformed

	private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
		setVisible(false);
	}//GEN-LAST:event_cancelActionPerformed

	private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
		if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
			int row = table.getSelectedRow();
			
			JOptionPane pane = new JOptionPane(
					"Waiting for \"" + controlElements[row].name + "\" input...", 
					JOptionPane.QUESTION_MESSAGE,
					JOptionPane.DEFAULT_OPTION) {
						
			};
			
			final JDialog dialog = pane.createDialog(this, "");
			final InputDetector detector = new InputDetector();
			
			Timer timer = new Timer(100, new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					if (detector.detect()) {
						dialog.setVisible(false);
					}
				}
			});
			
			timer.start();
			dialog.setVisible(true);
			timer.stop();
			
			if (detector.getController() != null && detector.getComponent() != null) {
				controlElements[row] = new ControlElement(
						controlElements[row].name, 
						detector.getController().getName(),
						detector.getComponent().getIdentifier().getName(),
						detector.getInverted());
			
				updateTable();
			}
		}
	}//GEN-LAST:event_tableMouseClicked

	private void updateTable() {
		DefaultTableModel m = new DefaultTableModel() {
			@Override
			public boolean isCellEditable(int rowIndex, int mColIndex) {
				return false;
			}			
		};

		m.setColumnIdentifiers(new String[]{"Control", "Device", "Component", "Inverted"});
		
		for (ControlElement c : controlElements)
			m.addRow(new String[]{c.name, c.controller, c.component, c.inverted ? "1" : "0"});
		
		table.setModel(m);
	}
	
	private class ControlElement {
		public ControlElement(String name, String controller, String component, boolean inverted) {
			this.name = makeNotNull(name);
			this.controller = makeNotNull(controller);
			this.component = makeNotNull(component);
			this.inverted = inverted;
		}
		
		private String makeNotNull(String s) {
			return (s != null || s.isEmpty()) ? s : "(none)";
		}
		
		public final String name;
		public final String controller;
		public final String component;
		public final boolean inverted;
	}
	
	private final ControlElement[] controlElements;
	private static final String[] controlNames = new String[]{
		"ailerons", "elevator", "rudder", "throttle", "flaps0", "flaps1", "flaps2", "ignition-off", 
		"cmd-auto", "cmd-manual", "cmd-futaba", "cmd-abort", "cmd-emergency"};
	
	
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables
}
